<!--
 * @FileDescription: 面包屑历史记录组件，该组件可以通过localStorage来实现不同组件之间的通信，并且在不同页面之间可以共享
 * @Author: yijiamu
 * @Date: 2022-05-08 15:17:25
 * @LastEditors: yijiamu
 * @LastEditTime: 2022-05-08 15:17:25
 -->

<template>
  <div class="crumb">
    <div class="functionContainer">
      <h4 v-if="historyList.length">搜索历史</h4>
      <el-button v-if="historyList.length" @click="clearAllHistory" size="mini">清空所有</el-button>
    </div>
    <ul class="placeList">
      <li v-for="(item, index) in historyList" :key="index" >
        <el-button size="mini" class="historyItem" round @click="choiceHistory(item)">{{item}}<i class="el-icon-close" @click="clearOneHistory(item)"></i></el-button>
      </li>
    </ul>
  </div>
</template>

<script lang="ts">
import { Component, Prop, Vue } from 'vue-property-decorator';
import {getStore, setStore} from "@/utils/utils";

@Component({})
export default class crumbsHistoryCom extends Vue {
  @Prop() historyListName !: string;  //localStorage中的键名
  private historyList !: string[];  //展示使用的historyList面包屑列表
  beforeMount(){
    this.initHistoryData();
  }
   /**
     * @description: 初始化用户信息
     * @param {void}
     * @return {void}
     */
  //初始化历史信息
  private initHistoryData(){
    //获取搜索历史记录
    if (getStore(this.historyListName)) {
      this.historyList = JSON.parse(getStore(this.historyListName) as  string);
    }else{
      this.historyList = [];
    }
    this.$forceUpdate()
  }

   /**
    * @description: 删除所有本地的搜索历史，并且初始化页面的历史
    * @return {void}
    */

  private clearAllHistory(){
    setStore(this.historyListName,[])
    this.$emit('putHistoryList',[])
    this.initHistoryData();
  }

   /**
    * @description: 删除整个面包屑
    * @return {void}
    * @param name
    */

  private clearOneHistory(name:string){
    let newPlaceHistory = this.historyList.filter((item:string)=>{
      return item !== name
    })
    //直接设置到localstorage
    setStore(this.historyListName,newPlaceHistory)
    this.initHistoryData();
  }

   /**
    * @description: 在历史搜素中选择一个记录并进入
    * @return {void}
    * @param item
    */

  private choiceHistory(item:string){
    // 上传点击的面包屑的值
    this.$emit('putHistoryValue',item)
  }
}
</script>

<!-- Add "scoped" attribute to limit CSS to this component only -->
<style scoped lang="less">
.crumb {
  margin: 10px 12px 30px 12px;
  ul,ol,li {
    list-style: none;
    margin: 0;
    padding: 0;
  }
  .functionContainer {
    margin: 10px 0;
    display: flex;
    justify-content: space-between;
    h4 {
      margin: 10px 0;
    }
    .el-button {
      border: none;
      background-color: #f5f5f5;
    }
  }
  .placeList {
    display: flex;
    flex-wrap: wrap;
    .historyItem {
      margin: 10px 4px;
      color: #333333;
      padding: 12px 16px ;
      .el-icon-close{
        margin-left: 4px;
      }
    }
  }
}

</style>
